using net_work.Common.Request;
using net_work.Common.Result;
using net_work.Data.DTO.Cou;
using net_work.Data.Entity.Cou;
using net_work.Data.Enum.Cou;
using net_work.IRepository.Cou;
using net_work.IRepository.Sys;
using net_work.IService.Cou;

namespace net_work.Service.Cou;

public class TeacherTeachingService(
    ITeacherTeachingRepository teacherTeachingRepository,
    ITeacherRepository teacherRepository,
    ITeachingRepository teachingRepository)
    : ITeacherTeachingService
{
    public Task<PagedResult<TeacherTeaching>> GetTeacherTeachingsPagedAsync(PagedRequest request)
    {
        return teacherTeachingRepository.GetPagedAsync(request);
    }

    public Task<TeacherTeaching?> SelectByIdAsync(long teacherTeachingId)
    {
        return teacherTeachingRepository.GetByIdAsync(teacherTeachingId);
    }

    public async Task<long> InsertTeacherTeaching(TeacherTeachingAddRequest teacherTeachingAddRequest)
    {
        var teaching = await teachingRepository.GetByIdAsync(teacherTeachingAddRequest.TeachId);
        if (teaching == null)
        {
            return -1;
        }

        if (teaching.TeachStatus == TeachStatus.Release)
        {
            return -1;
        }

        var teacher = await teacherRepository.GetByIdAsync(teacherTeachingAddRequest.TeacherId);
        if (teacher == null)
        {
            return -1;
        }

        return await teacherTeachingRepository.InsertAsync(teacherTeachingAddRequest);
    }

    public async Task<int> UpdateTeacherTeaching(TeacherTeachingUpdateRequest teacherTeachingUpdateRequest)
    {
        if (teacherTeachingUpdateRequest.Id <= 0)
        {
            return -1;
        }

        var teaching = await teachingRepository.GetByIdAsync(teacherTeachingUpdateRequest.TeachId);
        if (teaching == null)
        {
            return -1;
        }

        if (teaching.TeachStatus == TeachStatus.Release)
        {
            return -1;
        }

        var teacher = await teacherRepository.GetByIdAsync(teacherTeachingUpdateRequest.TeacherId);
        if (teacher == null)
        {
            return -1;
        }

        return await teacherTeachingRepository.UpdateAsync(teacherTeachingUpdateRequest) ? 1 : -1;
    }

    public async Task<int> DeleteTeacherTeachingByIds(List<long> ids)
    {
        foreach (var id in ids)
        {
            var teacherTeaching = await teacherTeachingRepository.GetByIdAsync(id);
            if (teacherTeaching == null)
            {
                continue;
            }

            var teaching = await teachingRepository.GetByIdAsync(teacherTeaching.TeachId);
            if (teaching == null)
            {
                return -1;
            }

            if (teaching.TeachStatus == TeachStatus.Release)
            {
                return -1;
            }
        }

        return await teacherTeachingRepository.DeleteByIdsAsync(ids) ? 1 : -1;
    }
}